# src/web_controller.py
from flask import render_template
import pandas as pd
from src.predict import TalentAttritionPredict
import os


class WebController:
    def __init__(self):
        self.predictor = None
        self._initialize_predictor()

    def _initialize_predictor(self):
        """初始化预测器"""
        try:
            self.predictor = TalentAttritionPredict()
        except Exception as e:
            print(f"预测器初始化失败: {e}")
            self.predictor = None

    def get_index_page(self):
        """获取主页"""
        # 默认测试数据
        default_data = {
            "Age": 30,
            "BusinessTravel": "Travel_Rarely",
            "Department": "Research & Development",
            "DistanceFromHome": 10,
            "Education": 3,
            "EducationField": "Life Sciences",
            "EmployeeNumber": 1234,
            "EnvironmentSatisfaction": 3,
            "Gender": "Male",
            "JobInvolvement": 3,
            "JobLevel": 2,
            "JobRole": "Research Scientist",
            "JobSatisfaction": 4,
            "MaritalStatus": "Married",
            "MonthlyIncome": 5000,
            "NumCompaniesWorked": 1,
            "OverTime": "No",
            "PercentSalaryHike": 13,
            "PerformanceRating": 3,
            "RelationshipSatisfaction": 4,
            "StockOptionLevel": 1,
            "TotalWorkingYears": 5,
            "TrainingTimesLastYear": 3,
            "WorkLifeBalance": 3,
            "YearsAtCompany": 3,
            "YearsInCurrentRole": 2,
            "YearsSinceLastPromotion": 1,
            "YearsWithCurrManager": 1
        }

        # 检查模板是否存在
        try:
            # 获取Flask应用实例
            from flask import current_app
            template_path = os.path.join(current_app.template_folder, 'index.html')
            if os.path.exists(template_path):
                return render_template('index.html', default_data=default_data)
            else:
                # 如果模板不存在，返回简单的HTML表单
                return self._get_simple_index_page(default_data)
        except Exception as e:
            print(f"渲染模板时出错: {e}")
            return self._get_simple_index_page(default_data)

    def _get_simple_index_page(self, default_data):
        """获取简单的HTML主页"""
        return f"""
        <!DOCTYPE html>
        <html>
        <head>
            <title>人才流失预测系统</title>
            <meta charset="utf-8">
            <style>
                body {{ font-family: Arial, sans-serif; margin: 40px; }}
                .form-group {{ margin-bottom: 15px; }}
                label {{ display: inline-block; width: 200px; }}
                input, select {{ padding: 5px; margin: 5px 0; }}
                button {{ background-color: #007bff; color: white; padding: 10px 20px; border: none; cursor: pointer; }}
                button:hover {{ background-color: #0056b3; }}
            </style>
        </head>
        <body>
            <h1>人才流失预测系统</h1>
            <form method="POST" action="/predict">
                <div class="form-group">
                    <label for="Age">年龄:</label>
                    <input type="number" id="Age" name="Age" value="{default_data['Age']}" required>
                </div>

                <div class="form-group">
                    <label for="BusinessTravel">出差频率:</label>
                    <select id="BusinessTravel" name="BusinessTravel">
                        <option value="Travel_Rarely" {"selected" if default_data['BusinessTravel'] == 'Travel_Rarely' else ""}>偶尔出差</option>
                        <option value="Travel_Frequently" {"selected" if default_data['BusinessTravel'] == 'Travel_Frequently' else ""}>经常出差</option>
                        <option value="Non-Travel" {"selected" if default_data['BusinessTravel'] == 'Non-Travel' else ""}>不出差</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="Department">部门:</label>
                    <select id="Department" name="Department">
                        <option value="Research & Development" {"selected" if default_data['Department'] == 'Research & Development' else ""}>研发部</option>
                        <option value="Sales" {"selected" if default_data['Department'] == 'Sales' else ""}>销售部</option>
                        <option value="Human Resources" {"selected" if default_data['Department'] == 'Human Resources' else ""}>人力资源部</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="DistanceFromHome">距离家庭距离:</label>
                    <input type="number" id="DistanceFromHome" name="DistanceFromHome" value="{default_data['DistanceFromHome']}">
                </div>

                <div class="form-group">
                    <label for="Education">教育水平:</label>
                    <input type="number" id="Education" name="Education" value="{default_data['Education']}">
                </div>

                <div class="form-group">
                    <label for="EducationField">教育领域:</label>
                    <select id="EducationField" name="EducationField">
                        <option value="Life Sciences" {"selected" if default_data['EducationField'] == 'Life Sciences' else ""}>生命科学</option>
                        <option value="Medical" {"selected" if default_data['EducationField'] == 'Medical' else ""}>医学</option>
                        <option value="Marketing" {"selected" if default_data['EducationField'] == 'Marketing' else ""}>市场营销</option>
                        <option value="Technical Degree" {"selected" if default_data['EducationField'] == 'Technical Degree' else ""}>技术学位</option>
                        <option value="Human Resources" {"selected" if default_data['EducationField'] == 'Human Resources' else ""}>人力资源</option>
                        <option value="Other" {"selected" if default_data['EducationField'] == 'Other' else ""}>其他</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="EmployeeNumber">员工编号:</label>
                    <input type="number" id="EmployeeNumber" name="EmployeeNumber" value="{default_data['EmployeeNumber']}">
                </div>

                <div class="form-group">
                    <label for="Gender">性别:</label>
                    <select id="Gender" name="Gender">
                        <option value="Male" {"selected" if default_data['Gender'] == 'Male' else ""}>男性</option>
                        <option value="Female" {"selected" if default_data['Gender'] == 'Female' else ""}>女性</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="JobRole">职位:</label>
                    <select id="JobRole" name="JobRole">
                        <option value="Research Scientist" {"selected" if default_data['JobRole'] == 'Research Scientist' else ""}>研究科学家</option>
                        <option value="Laboratory Technician" {"selected" if default_data['JobRole'] == 'Laboratory Technician' else ""}>实验室技术员</option>
                        <option value="Research Director" {"selected" if default_data['JobRole'] == 'Research Director' else ""}>研究总监</option>
                        <option value="Manufacturing Director" {"selected" if default_data['JobRole'] == 'Manufacturing Director' else ""}>制造总监</option>
                        <option value="Healthcare Representative" {"selected" if default_data['JobRole'] == 'Healthcare Representative' else ""}>医疗代表</option>
                        <option value="Manager" {"selected" if default_data['JobRole'] == 'Manager' else ""}>经理</option>
                        <option value="Sales Executive" {"selected" if default_data['JobRole'] == 'Sales Executive' else ""}>销售主管</option>
                        <option value="Sales Representative" {"selected" if default_data['JobRole'] == 'Sales Representative' else ""}>销售代表</option>
                        <option value="Human Resources" {"selected" if default_data['JobRole'] == 'Human Resources' else ""}>人力资源</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="JobLevel">职位级别:</label>
                    <input type="number" id="JobLevel" name="JobLevel" value="{default_data['JobLevel']}">
                </div>

                <div class="form-group">
                    <label for="MonthlyIncome">月收入:</label>
                    <input type="number" id="MonthlyIncome" name="MonthlyIncome" value="{default_data['MonthlyIncome']}">
                </div>

                <div class="form-group">
                    <label for="MaritalStatus">婚姻状况:</label>
                    <select id="MaritalStatus" name="MaritalStatus">
                        <option value="Single" {"selected" if default_data['MaritalStatus'] == 'Single' else ""}>单身</option>
                        <option value="Married" {"selected" if default_data['MaritalStatus'] == 'Married' else ""}>已婚</option>
                        <option value="Divorced" {"selected" if default_data['MaritalStatus'] == 'Divorced' else ""}>离异</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="NumCompaniesWorked">工作过的公司数量:</label>
                    <input type="number" id="NumCompaniesWorked" name="NumCompaniesWorked" value="{default_data['NumCompaniesWorked']}">
                </div>

                <div class="form-group">
                    <label for="OverTime">是否加班:</label>
                    <select id="OverTime" name="OverTime">
                        <option value="No" {"selected" if default_data['OverTime'] == 'No' else ""}>否</option>
                        <option value="Yes" {"selected" if default_data['OverTime'] == 'Yes' else ""}>是</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="PercentSalaryHike">薪资涨幅百分比:</label>
                    <input type="number" id="PercentSalaryHike" name="PercentSalaryHike" value="{default_data['PercentSalaryHike']}">
                </div>

                <div class="form-group">
                    <label for="PerformanceRating">绩效评级:</label>
                    <input type="number" id="PerformanceRating" name="PerformanceRating" value="{default_data['PerformanceRating']}">
                </div>

                <div class="form-group">
                    <label for="TotalWorkingYears">总工作年限:</label>
                    <input type="number" id="TotalWorkingYears" name="TotalWorkingYears" value="{default_data['TotalWorkingYears']}">
                </div>

                <div class="form-group">
                    <label for="TrainingTimesLastYear">去年培训次数:</label>
                    <input type="number" id="TrainingTimesLastYear" name="TrainingTimesLastYear" value="{default_data['TrainingTimesLastYear']}">
                </div>

                <div class="form-group">
                    <label for="YearsAtCompany">在公司年数:</label>
                    <input type="number" id="YearsAtCompany" name="YearsAtCompany" value="{default_data['YearsAtCompany']}">
                </div>

                <div class="form-group">
                    <label for="YearsInCurrentRole">在当前角色年数:</label>
                    <input type="number" id="YearsInCurrentRole" name="YearsInCurrentRole" value="{default_data['YearsInCurrentRole']}">
                </div>

                <div class="form-group">
                    <label for="YearsSinceLastPromotion">上次晋升以来年数:</label>
                    <input type="number" id="YearsSinceLastPromotion" name="YearsSinceLastPromotion" value="{default_data['YearsSinceLastPromotion']}">
                </div>

                <div class="form-group">
                    <label for="YearsWithCurrManager">与当前经理共事年数:</label>
                    <input type="number" id="YearsWithCurrManager" name="YearsWithCurrManager" value="{default_data['YearsWithCurrManager']}">
                </div>

                <div class="form-group">
                    <label for="EnvironmentSatisfaction">环境满意度:</label>
                    <select id="EnvironmentSatisfaction" name="EnvironmentSatisfaction">
                        <option value="1" {"selected" if default_data['EnvironmentSatisfaction'] == 1 else ""}>1 - 非常不满意</option>
                        <option value="2" {"selected" if default_data['EnvironmentSatisfaction'] == 2 else ""}>2 - 不满意</option>
                        <option value="3" {"selected" if default_data['EnvironmentSatisfaction'] == 3 else ""}>3 - 满意</option>
                        <option value="4" {"selected" if default_data['EnvironmentSatisfaction'] == 4 else ""}>4 - 非常满意</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="JobSatisfaction">工作满意度:</label>
                    <select id="JobSatisfaction" name="JobSatisfaction">
                        <option value="1" {"selected" if default_data['JobSatisfaction'] == 1 else ""}>1 - 非常不满意</option>
                        <option value="2" {"selected" if default_data['JobSatisfaction'] == 2 else ""}>2 - 不满意</option>
                        <option value="3" {"selected" if default_data['JobSatisfaction'] == 3 else ""}>3 - 满意</option>
                        <option value="4" {"selected" if default_data['JobSatisfaction'] == 4 else ""}>4 - 非常满意</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="RelationshipSatisfaction">关系满意度:</label>
                    <select id="RelationshipSatisfaction" name="RelationshipSatisfaction">
                        <option value="1" {"selected" if default_data['RelationshipSatisfaction'] == 1 else ""}>1 - 非常不满意</option>
                        <option value="2" {"selected" if default_data['RelationshipSatisfaction'] == 2 else ""}>2 - 不满意</option>
                        <option value="3" {"selected" if default_data['RelationshipSatisfaction'] == 3 else ""}>3 - 满意</option>
                        <option value="4" {"selected" if default_data['RelationshipSatisfaction'] == 4 else ""}>4 - 非常满意</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="JobInvolvement">工作投入度:</label>
                    <select id="JobInvolvement" name="JobInvolvement">
                        <option value="1" {"selected" if default_data['JobInvolvement'] == 1 else ""}>1 - 低</option>
                        <option value="2" {"selected" if default_data['JobInvolvement'] == 2 else ""}>2 - 中等</option>
                        <option value="3" {"selected" if default_data['JobInvolvement'] == 3 else ""}>3 - 高</option>
                        <option value="4" {"selected" if default_data['JobInvolvement'] == 4 else ""}>4 - 非常高</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="WorkLifeBalance">工作生活平衡:</label>
                    <select id="WorkLifeBalance" name="WorkLifeBalance">
                        <option value="1" {"selected" if default_data['WorkLifeBalance'] == 1 else ""}>1 - 非常差</option>
                        <option value="2" {"selected" if default_data['WorkLifeBalance'] == 2 else ""}>2 - 差</option>
                        <option value="3" {"selected" if default_data['WorkLifeBalance'] == 3 else ""}>3 - 好</option>
                        <option value="4" {"selected" if default_data['WorkLifeBalance'] == 4 else ""}>4 - 非常好</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="StockOptionLevel">股票期权级别:</label>
                    <select id="StockOptionLevel" name="StockOptionLevel">
                        <option value="0" {"selected" if default_data['StockOptionLevel'] == 0 else ""}>0 - 无</option>
                        <option value="1" {"selected" if default_data['StockOptionLevel'] == 1 else ""}>1 - 低</option>
                        <option value="2" {"selected" if default_data['StockOptionLevel'] == 2 else ""}>2 - 中</option>
                        <option value="3" {"selected" if default_data['StockOptionLevel'] == 3 else ""}>3 - 高</option>
                    </select>
                </div>

                <button type="submit">预测流失风险</button>
            </form>
        </body>
        </html>
        """, 200

    def predict_from_form(self, form_data):
        """从表单数据进行预测"""
        try:
            if self.predictor is None:
                self._initialize_predictor()

            if self.predictor is None:
                return {"error": "预测器未初始化"}, 500

            # 转换表单数据
            processed_data = self._process_form_data(form_data)

            # 创建DataFrame
            input_data = pd.DataFrame([processed_data])

            # 执行特征工程
            processed_features = self.predictor.feature_engineering(input_data)

            # 进行预测
            prediction_proba = self.predictor.model.predict_proba(processed_features)[:, 1]
            prediction = (prediction_proba >= self.predictor.threshold).astype(int)

            # 返回结果
            result = {
                "prediction": int(prediction[0]),
                "probability": float(prediction_proba[0]),
                "threshold": float(self.predictor.threshold),
                "message": "员工流失风险高" if prediction[0] == 1 else "员工流失风险低"
            }

            return result, 200

        except Exception as e:
            return {"error": f"预测过程中发生错误: {str(e)}"}, 500

    def _process_form_data(self, form_data):
        """处理表单数据"""
        processed = {}

        # 数值型字段
        numeric_fields = [
            'Age', 'DistanceFromHome', 'Education', 'EmployeeNumber',
            'EnvironmentSatisfaction', 'JobInvolvement', 'JobLevel',
            'JobSatisfaction', 'MonthlyIncome', 'NumCompaniesWorked',
            'PercentSalaryHike', 'PerformanceRating', 'RelationshipSatisfaction',
            'StockOptionLevel', 'TotalWorkingYears', 'TrainingTimesLastYear',
            'WorkLifeBalance', 'YearsAtCompany', 'YearsInCurrentRole',
            'YearsSinceLastPromotion', 'YearsWithCurrManager'
        ]

        # 处理数值型字段
        for field in numeric_fields:
            value = form_data.get(field)
            if value is not None:
                try:
                    processed[field] = int(value)
                except ValueError:
                    try:
                        processed[field] = float(value)
                    except ValueError:
                        processed[field] = 0
            else:
                processed[field] = 0

        # 处理文本型字段
        text_fields = [
            'BusinessTravel', 'Department', 'EducationField', 'Gender',
            'JobRole', 'MaritalStatus', 'OverTime'
        ]

        for field in text_fields:
            value = form_data.get(field)
            processed[field] = value if value is not None else ""

        return processed

    def get_api_documentation(self):
        """获取API文档"""
        documentation = {
            "title": "人才流失预测系统 - API文档",
            "description": "这是一个用于预测员工流失风险的系统",
            "endpoints": {
                "web_interface": {
                    "url": "/",
                    "method": "GET",
                    "description": "Web界面"
                },
                "api_predict": {
                    "url": "/api/predict",
                    "method": "POST",
                    "description": "API预测接口",
                    "request_format": {
                        "content_type": "application/json",
                        "parameters": {
                            "Age": "整数，年龄",
                            "BusinessTravel": "字符串，出差频率",
                            "Department": "字符串，部门",
                            "DistanceFromHome": "整数，距离家庭的距离",
                            "Education": "整数，教育水平",
                            "EducationField": "字符串，教育领域",
                            "EmployeeNumber": "整数，员工编号",
                            "EnvironmentSatisfaction": "整数，环境满意度",
                            "Gender": "字符串，性别",
                            "JobInvolvement": "整数，工作投入度",
                            "JobLevel": "整数，工作级别",
                            "JobRole": "字符串，工作角色",
                            "JobSatisfaction": "整数，工作满意度",
                            "MaritalStatus": "字符串，婚姻状况",
                            "MonthlyIncome": "整数，月收入",
                            "NumCompaniesWorked": "整数，工作过的公司数量",
                            "OverTime": "字符串，是否加班",
                            "PercentSalaryHike": "整数，薪资涨幅百分比",
                            "PerformanceRating": "整数，绩效评级",
                            "RelationshipSatisfaction": "整数，关系满意度",
                            "StockOptionLevel": "整数，股票期权级别",
                            "TotalWorkingYears": "整数，总工作年限",
                            "TrainingTimesLastYear": "整数，去年培训次数",
                            "WorkLifeBalance": "整数，工作生活平衡",
                            "YearsAtCompany": "整数，在公司年数",
                            "YearsInCurrentRole": "整数，在当前角色年数",
                            "YearsSinceLastPromotion": "整数，上次晋升以来年数",
                            "YearsWithCurrManager": "整数，与当前经理共事年数"
                        }
                    },
                    "response_format": {
                        "prediction": "整数，预测结果（0表示不会流失，1表示会流失）",
                        "probability": "浮点数，流失概率",
                        "threshold": "浮点数，判断阈值",
                        "message": "字符串，风险评估信息"
                    }
                }
            }
        }

        return documentation
